package com.kxmall.huishou.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.kxmall.categorize.domain.bo.HsWasteCategorizeBo;
import com.kxmall.categorize.domain.vo.HsWasteCategorizeVo;
import com.kxmall.categorize.service.IHsWasteCategorizeService;
import com.kxmall.common.core.page.TableDataInfo;
import com.kxmall.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.kxmall.common.utils.StringUtils;
import com.kxmall.count.countVO.RecoveryChartVO;
import com.kxmall.huishou.domain.vo.HsAppointmentOrderVo;
import com.kxmall.huishou.domain.vo.HsSettlementOrderVo;
import com.kxmall.huishou.mapper.HsAppointmentOrderMapper;
import com.kxmall.huishou.mapper.HsSettlementOrderMapper;
import com.kxmall.huishou.service.IHsAppointmentOrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.kxmall.huishou.domain.bo.HsUserWasteBo;
import com.kxmall.huishou.domain.vo.HsUserWasteVo;
import com.kxmall.huishou.domain.HsUserWaste;
import com.kxmall.huishou.mapper.HsUserWasteMapper;
import com.kxmall.huishou.service.IHsUserWasteService;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;

/**
 * 回收废品信息Service业务层处理
 *
 * @author kxmall
 * @date 2023-11-24
 */
@RequiredArgsConstructor
@Service
public class HsUserWasteServiceImpl implements IHsUserWasteService {

    private final HsUserWasteMapper baseMapper;

    private final HsAppointmentOrderMapper hsAppointmentOrderMapper;

    private final HsSettlementOrderMapper hsSettlementOrderMapper;

    /**
     * 查询回收废品信息
     */
    @Override
    public HsUserWasteVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询回收废品信息列表
     */
    @Override
    public TableDataInfo<HsUserWasteVo> queryPageList(HsUserWasteBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<HsUserWaste> lqw = buildQueryWrapper(bo);
        Page<HsUserWasteVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询回收废品信息列表
     */
    @Override
    public List<HsUserWasteVo> queryList(HsUserWasteBo bo) {
        LambdaQueryWrapper<HsUserWaste> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<HsUserWaste> buildQueryWrapper(HsUserWasteBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<HsUserWaste> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getOrderId() != null, HsUserWaste::getOrderId, bo.getOrderId());
        lqw.eq(bo.getOrderType() != null, HsUserWaste::getOrderType, bo.getOrderType());
        lqw.eq(bo.getCategorizeId() != null, HsUserWaste::getCategorizeId, bo.getCategorizeId());
//        lqw.like(StringUtils.isNotBlank(bo.getCategorizeName()), HsUserWaste::getCategorizeName, bo.getCategorizeName());
        return lqw;
    }

    /**
     * 新增回收废品信息
     */
    @Override
    public Boolean insertByBo(HsUserWasteBo bo) {
        HsUserWaste add = BeanUtil.toBean(bo, HsUserWaste.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 新增回收废品信息列表
     */
    @Override
    public Boolean insertOrUpdateByBoList(List<HsUserWasteBo> boList) {

        if(boList == null || boList.size() == 0){
            return false;
        }

        List<HsUserWaste> hsUserWasteList = new ArrayList<HsUserWaste>();
        for(HsUserWasteBo hsUserWasteBo : boList){
            HsUserWaste hsUserWaste = BeanUtil.toBean(hsUserWasteBo, HsUserWaste.class);
            validEntityBeforeSave(hsUserWaste);
            hsUserWasteList.add(hsUserWaste);

        }

        boolean flag = baseMapper.insertOrUpdateBatch(hsUserWasteList);
        return flag;
    }

    /**
     * 修改回收废品信息
     */
    @Override
    public Boolean updateByBo(HsUserWasteBo bo) {
        HsUserWaste update = BeanUtil.toBean(bo, HsUserWaste.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(HsUserWaste entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除回收废品信息
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid, Long userId,long orderType) {
        if(ids == null){
            return false;
        }
        List<Long> deleteIds = new ArrayList<>();
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
            for(Long id : ids){
                HsUserWasteVo hsUserWasteVo = baseMapper.selectVoById(id);
                if(hsUserWasteVo == null || hsUserWasteVo.getOrderType().longValue() != orderType){
                    continue;
                }
                if(orderType == 0l){
                    HsAppointmentOrderVo hsAppointmentOrderVo = hsAppointmentOrderMapper.selectVoById(hsUserWasteVo.getOrderId());
                    if(hsAppointmentOrderVo == null || hsAppointmentOrderVo.getUserId().longValue() != userId.longValue()
                            || hsAppointmentOrderVo.getStatus().longValue() != 0l ){
                        continue;
                    }
                }else {
                    HsSettlementOrderVo hsSettlementOrderVo = hsSettlementOrderMapper.selectVoById(hsUserWasteVo.getOrderId());
                    if(hsSettlementOrderVo == null || hsSettlementOrderVo.getRiderId().longValue() != userId.longValue()){
                        continue;
                    }
                    if(hsSettlementOrderVo.getStatus().longValue() == 3l ||hsSettlementOrderVo.getStatus().longValue() == 4l
                            || hsSettlementOrderVo.getStatus().longValue() == 6l || hsSettlementOrderVo.getStatus().longValue() == 1l){
                        continue;
                    }
                }

                deleteIds.add(id);
            }
        }
        if(deleteIds.size() == 0){
            return false;
        }
        return baseMapper.deleteBatchIds(deleteIds) > 0;
    }

    @Override
    public void deletaByOrderId(Long id) {
        baseMapper.deletaByOrderId(id);
    }

    private final IHsWasteCategorizeService iHsWasteCategorizeService;

    @Override
    public List<RecoveryChartVO> queryChartType(Wrapper<HsUserWaste> query) {
        HsWasteCategorizeBo bo = new HsWasteCategorizeBo();
        bo.setParentId(0L);
        List<HsWasteCategorizeVo> categorizeVoList = iHsWasteCategorizeService.queryList(bo);

        List<HsUserWaste> hsUserWasteVos = this.baseMapper.selectList(query);
        List<RecoveryChartVO> chartList = new ArrayList<>();

        // 循环总废品分类
        for(HsWasteCategorizeVo hsWasteCategorizeVo :categorizeVoList){
            // 查询子废品分类
            List<HsWasteCategorizeVo> chidList = iHsWasteCategorizeService.queryListByParentId(hsWasteCategorizeVo.getId());
            RecoveryChartVO chart = new RecoveryChartVO();
            chart.setName(hsWasteCategorizeVo.getName());

            // 获取第一个子分类的单位作为该大分类的单位（假设同一大分类下的子分类单位相同）
            String originalUnit = "吨"; // 默认单位
            if (CollUtil.isNotEmpty(chidList)) {
                String firstChildUnit = chidList.get(0).getUnit();
                if (StrUtil.isNotBlank(firstChildUnit)) {
                    originalUnit = firstChildUnit;
                }
            }

            // 用于累计计算的数值
            BigDecimal totalValue = BigDecimal.ZERO;

            // 循环废品回收信息
            for (HsUserWaste hsUserWasteVo : hsUserWasteVos) {
                // 该废品分类属于大分类则相加
                for (HsWasteCategorizeVo categorizeVo : chidList) {
                    if(Objects.equals(categorizeVo.getId(), hsUserWasteVo.getCategorizeId())){
                        BigDecimal weight = hsUserWasteVo.getWeight();
                        if (weight != null) {
                            // 根据单位进行转换为吨
                            BigDecimal convertedValue = convertToStandardUnit(weight, categorizeVo.getUnit());
                            totalValue = totalValue.add(convertedValue);
                        }
                    }
                }
            }

            // 设置原始数值（转换前）
            chart.setValueNumber(totalValue.toString());

            // 格式化最终的显示值（包含单位）
            chart.setValue(formatValueWithUnit(totalValue, originalUnit));

            // 设置最终单位（根据转换后的值确定）
            chart.setUnit(getFinalUnit(totalValue, originalUnit));
            chartList.add(chart);
        }
        return chartList;
    }

    /**
     * 将不同单位的值转换为标准单位
     * kg、g -> 转换为吨
     * 台、辆 -> 保持原值（计数）
     */
    private BigDecimal convertToStandardUnit(BigDecimal value, String unit) {
        if (value == null || StrUtil.isBlank(unit)) {
            return value != null ? value : BigDecimal.ZERO;
        }

        String unitLower = unit.toLowerCase().trim();
        switch (unitLower) {
            case "kg":
            case "千克":
                // kg转吨：1kg = 0.001吨，即除以1000
                // 例：1000kg = 1吨，保留6位小数用于精确计算
                return value.divide(new BigDecimal("1000"), 6, RoundingMode.HALF_UP);
            case "g":
            case "克":
                // g转吨：1g = 0.000001吨，即除以1000000
                // 例：1000000g = 1吨，保留6位小数用于精确计算
                return value.divide(new BigDecimal("1000000"), 6, RoundingMode.HALF_UP);
            case "台":
            case "辆":
            case "个":
            case "件":
                // 计数单位保持原值
                return value;
            case "吨":
            case "t":
            default:
                // 默认已经是吨或其他重量单位，保持原值
                return value;
        }
    }

    /**
     * 格式化数值并添加单位
     * @param value 数值
     * @param unit 单位
     * @return 格式化后的字符串（包含单位）
     */
    private String formatValueWithUnit(BigDecimal value, String unit) {
        if (value == null) {
            value = BigDecimal.ZERO;
        }

        String unitLower = unit.toLowerCase().trim();
        switch (unitLower) {
            case "吨":
            case "t":
            case "kg":
            case "千克":
            case "g":
            case "克":
                // 重量类型：根据大小决定显示吨还是千吨
                // 注意：这里的value已经是转换为吨的数值了
                BigDecimal formattedWeight = value.setScale(2, RoundingMode.HALF_UP);
                if (formattedWeight.compareTo(new BigDecimal("1000")) >= 0) {
                    BigDecimal weightInKiloTons = formattedWeight.divide(new BigDecimal("1000"), 2, RoundingMode.HALF_UP);
                    return weightInKiloTons.toString() + "千吨";
                } else {
                    return formattedWeight.toString() + "吨";
                }
            case "台":
            case "辆":
            case "个":
            case "件":
                // 计数类型：只显示数字，不显示单位
                BigDecimal countValue = value.setScale(0, RoundingMode.HALF_UP);
                return countValue.toString();
            default:
                // 其他类型：保留2位小数
                BigDecimal defaultValue = value.setScale(2, RoundingMode.HALF_UP);
                return defaultValue.toString();
        }
    }

    /**
     * 获取最终显示单位
     * @param value 转换后的数值（吨）
     * @param originalUnit 原始单位
     * @return 最终显示单位
     */
    private String getFinalUnit(BigDecimal value, String originalUnit) {
        String unitLower = originalUnit.toLowerCase().trim();
        switch (unitLower) {
            case "吨":
            case "t":
            case "kg":
            case "千克":
            case "g":
            case "克":
                // 重量类型：根据转换后的值大小决定单位
                BigDecimal formattedWeight = value.setScale(2, RoundingMode.HALF_UP);
                return formattedWeight.compareTo(new BigDecimal("1000")) >= 0 ? "千吨" : "吨";
            default:
                // 计数类型保持原单位
                return originalUnit;
        }
    }
}
